/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import model.SocialMediaBericht;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

/**
 *
 * @author Matthy & Jelle
 */
public class TweetListenerService implements MessageListener {

  @Override
  public void onMessage(Message msg) {
    Reader in = null;
    try {
      in = new StringReader(((TextMessage) msg).getText().replaceAll("UTF", "utf"));
      SAXBuilder xmlBuilder = new SAXBuilder();


      Document doc = xmlBuilder.build(in);
      Element root = doc.getRootElement();
      Element datum = root.getChild("datum");
      Element netwerk = root.getChild("netwerk");
      Element film = root.getChild("film");
      Element tekst = root.getChild("tekst");

      SocialMediaBericht bericht = new SocialMediaBericht();
      DateFormat format = new SimpleDateFormat("dd-MM-yyyy");

      bericht.setDatum(format.parse(datum.getText()));
      bericht.setNetwerk(netwerk.getText());
      bericht.setFilmNaam(film.getText());
      bericht.setTekst(tekst.getText());

      new SocialMediaBerichtService().save(bericht);

    } catch (JMSException ex) {
      System.out.println(ex.getMessage());
    } catch (ParseException ex) {
      System.out.println(ex.getMessage());
    } catch (JDOMException ex) {
      System.out.println(ex.getMessage());
    } catch (IOException ex) {
      System.out.println(ex.getMessage());
    } finally {
      try {
        in.close();
      } catch (IOException ex) {
        System.out.println(ex.getMessage());
      }
    }
  }
}
